package com.two.screen.water.balance.net.api

import com.lzy.okgo.OkGo
import com.lzy.okrx2.adapter.ObservableBody
import com.two.screen.water.balance.bean.BaseBean
import com.two.screen.water.balance.bean.ServerGoods
import com.two.screen.water.balance.bean.database.*
import com.two.screen.water.balance.listener.ApiCallBack
import com.two.screen.water.balance.listener.MyObserver
import com.two.screen.water.balance.net.JsonConvert
import com.two.screen.water.balance.net.observer.NormalObserver
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.utils.*
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import org.greenrobot.greendao.query.WhereCondition

object CateProductApi {

    /*主页查询本地分类商品数据*/
    fun queryCateData(baseActivity: BaseActivity, apiCallBack: ApiCallBack? = null) {
        Observable.create(ObservableOnSubscribe<String> { e ->
            var conditionList = arrayListOf(
                CateDBDao.Properties.UserId.eq(DataApi.mUserId),//用户id
                CateDBDao.Properties.IsDeleted.eq(0)//0 正常 1删除
            )
            var list = App.mDaoMaster?.newSession()
                ?.queryBuilder(CateDB::class.java)
                ?.orderAsc(CateDBDao.Properties.Sort)
                ?.where(WhereCondition.StringCondition("1=1"), *conditionList.toTypedArray())
                ?.list()

            list?.forEach { it ->
                it.productDBList =
                    it.getProductDBList()?.sortedBy { it.sort }?.filter { f -> (f.userId.toString() == DataApi.mUserId) && f.isDeleted == 0 }
                d("queryCateData->list->${it.cateName}->${CommUtils.gson.toJson(list)}")
            }
            list = list?.filter { it.productDBList != null && it.productDBList.isNotEmpty() }
            if (list != null) e.onNext(CommUtils.gson.toJson(list)) else e.onError(Throwable("数据为空!"))
        })
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(baseActivity))
            .subscribe(object : MyObserver<String>() {
                override fun onNext(t: String) {
                    apiCallBack?.success(t)
                }

                override fun onError(t: Throwable) {
                    ToastUtil.showToast(t.message.toString())
                    apiCallBack?.fail(t)
                }
            })
    }

    /*Ai识别查询本地商品数据 通过拼音字母*/
    fun queryGoodsDataByPinYin(keyName: String?, apiCallBack: ApiCallBack? = null) {
        if (keyName == null) return
        Observable.create(ObservableOnSubscribe<String> { e ->
            var listCondition = arrayListOf(
                ProductDBDao.Properties.PinYinName.like("%$keyName%"),
                ProductDBDao.Properties.UserId.eq(DataApi.mUserId),
                ProductDBDao.Properties.IsDeleted.eq(0)//0 正常 1删除
                //ProductDBDao.Properties.PinYinFirstSpell.like("%$keyName%")
            )//模糊搜索查询
            var list =
                App.mDaoMaster?.newSession()?.queryBuilder(ProductDB::class.java)
                    ?.where(WhereCondition.StringCondition("1=1"), *listCondition.toTypedArray())
                    ?.orderAsc(ProductDBDao.Properties.Sort)
                    ?.list()

            if (list != null) e.onNext(CommUtils.gson.toJson(list)) else e.onError(Throwable("数据为空!"))
        })
            .compose(RxUtils.io())
            .subscribe(object : MyObserver<String>() {
                override fun onNext(t: String) {
                    apiCallBack?.success(t)
                }

                override fun onError(t: Throwable) {
                    ToastUtil.showToast(t.message.toString())
                    apiCallBack?.fail(t)
                }
            })
    }

    /*本地商品数据 异步*/
    fun queryAllGoodsDataAsync(apiCallBack: ApiCallBack? = null) {
        Observable.create(ObservableOnSubscribe<String> { e ->
            var conditionList = arrayListOf(
                ProductDBDao.Properties.UserId.eq(DataApi.mUserId),//用户id查询
                ProductDBDao.Properties.IsDeleted.eq(0)//0 正常 1删除
            )
            var list =
                App.mDaoMaster?.newSession()?.queryBuilder(ProductDB::class.java)
                    ?.where(WhereCondition.StringCondition("1=1"), *conditionList.toTypedArray())
                    ?.orderAsc(ProductDBDao.Properties.Sort)
                    ?.list()

            if (list != null) e.onNext(CommUtils.gson.toJson(list)) else e.onError(Throwable("数据为空!"))
        })
            .compose(RxUtils.io())
            .subscribe(object : MyObserver<String>() {
                override fun onNext(t: String) {
                    apiCallBack?.success(t)
                }

                override fun onError(t: Throwable) {
                    ToastUtil.showToast(t.message.toString())
                    apiCallBack?.fail(t)
                }
            })
    }

    /*本地商品数据 同步*/
    fun queryAllGoodsDataSync(apiCallBack: ApiCallBack? = null): MutableList<ProductDB>? {
        return try {
            var conditionList = arrayListOf(
                ProductDBDao.Properties.UserId.eq(DataApi.mUserId),//用户id查询
                ProductDBDao.Properties.IsDeleted.eq(0)//0 正常 1删除
            )
            App.mDaoMaster?.newSession()
                ?.queryBuilder(ProductDB::class.java)
                ?.where(WhereCondition.StringCondition("1=1"), *conditionList.toTypedArray())
                ?.orderAsc(ProductDBDao.Properties.Sort)
                ?.list()
        } catch (e: Exception) {
            d("queryAllGoodsDataSync->error:$e")
            null
        }
    }

    fun initCateProductData(serverGoods: ServerGoods?, baseActivity: BaseActivity, apiCallBack: ApiCallBack? = null) {
        Observable.create(ObservableOnSubscribe<String> { e ->
            serverGoods2LocalGoods(serverGoods)
            val list = App.mDaoMaster?.newSession()?.queryBuilder(CateDB::class.java)
                ?.list()
            d("list:${CommUtils.gson.toJson(list)}")
            e.onNext("")
            //if (list != null) e.onNext(CommUtils.gson.toJson(list)) else e.onError(Throwable("数据为空!"))
        })
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(baseActivity))
            .subscribe(object : MyObserver<String>() {
                override fun onNext(t: String) {
                    apiCallBack?.success(t)
                }

                override fun onError(t: Throwable) {
                    d("goods为空报错：${t.message}")
                    ToastUtil.showToast(t.message.toString())
                    apiCallBack?.fail(t)
                }
            })
    }

    /*服务器商品分类和商品数据转换成本地数据库*/
    private fun serverGoods2LocalGoods(serverGoods: ServerGoods?) {
        App.mDaoSession?.callInTx {
            //更新或插入。
            d("分类长度：${serverGoods?.list?.size}")
            serverGoods?.list?.forEach {
                d("每个分类：${it.name},商品长度：${it.goods?.size}")
            }

            serverGoods?.list?.forEach { cate ->
                val cateDB = CateDB().apply {
                    this.cateName = cate.name
                    this.cateId = cate.cate_id
                    this.id = cate.cate_id?.toLong() ?: 0L
                    this.userId = (DataApi.mUserId ?: DBApi.DEFAULT_ACCOUNT).toLong()
                    this.userName = DataApi.mUserName
                    this.productDBList = mutableListOf()
                    this.isDeleted = cate.is_deleted//
                    this.sort = cate.sort
                }
                App.mDaoSession?.cateDBDao?.insertOrReplace(cateDB)
                d("cateDB->id:${cateDB.id},cateId:${cateDB.cateId},cateName:${cateDB.cateName}")
                if (cate.goods != null && cate.goods!!.isNotEmpty()) {
                    cate.goods?.forEach { good ->
                        var productDB = ProductDB()

                        productDB.apply {
                            try {
                                this.isDeleted = good.is_deleted
                                this.productName = good.g_nm
                                this.productId = good.id?.toLong() ?: 0L
                                this.id = this.productId
                                this.cateName = cateDB.cateName
                                this.cateId = cateDB.id
                                this.giftPrice = "0.00"
                                this.logoImage = good.img
                                this.oriPrice = good.price
                                this.realPrice = good.price
                                this.unitName = good.specs
                                this.unitId = "1"
                                this.unitType = good.im_tp
                                this.sort = good.sort
                                this.invNum = good.inv_num ?: "0"

                                this.userId = (DataApi.mUserId ?: DBApi.DEFAULT_ACCOUNT).toLong()
                                this.userName = DataApi.mUserName
                                good.g_nm?.let { name ->
                                }
                            } catch (e: Exception) {
                                d("goods为空报错：${e}")
                            }
                        }
                        App.mDaoSession?.productDBDao?.insertOrReplace(productDB)
                    }
                }
            }
            true
        }
    }

    /*批量更新本地商品排序*/
    fun updateProductSort(list: List<ProductDB>, apiCallBack: ApiCallBack? = null) {
        Observable.create(ObservableOnSubscribe<String> { e ->
            App.mDaoSession?.productDBDao?.updateInTx(list)
            e.onNext(CommUtils.gson.toJson(list))
        })
            .compose(RxUtils.io())
            .subscribe(object : MyObserver<String>() {
                override fun onNext(t: String) {
                    apiCallBack?.success(t)
                }

                override fun onError(t: Throwable) {
                    ToastUtil.showToast(t.message.toString())
                    apiCallBack?.fail(t)
                }
            })

    }

    /*更新库存*/
    fun updateCateProductData(baseActivity: BaseActivity, apiCallBack: ApiCallBack? = null) {
        //TODO:无网或者关闭即可退出。
        if (!DataApi.mUseSimpleInventory || !DataApi.mIsConnectNet) return
        OkGo.post<BaseBean<ServerGoods>>(Urls.goodsList) //
            .headers(Params.getHeads())
            .converter(object : JsonConvert<BaseBean<ServerGoods>>() {}) //
            .adapt(ObservableBody())
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(baseActivity))
            .subscribe(object : NormalObserver<ServerGoods>(baseActivity) {
                override fun onSuccessNext(t: BaseBean<out ServerGoods>) {
                    Observable.create(ObservableOnSubscribe<String> { e ->
                        d("看看在什么线程：01->${Thread.currentThread().name}")
                        try {
                            d("看看在什么线程：02->${Thread.currentThread().name}")
                            serverGoods2LocalGoods(t.data)
                        } catch (t: Exception) {
                            e.onError(t)
                        }
                        e.onNext("")
                    })
                        .compose(RxUtils.io())
                        .compose(RxUtils.aLifecycle(baseActivity))
                        .subscribe(object : MyObserver<String>() {
                            override fun onNext(t: String) {
                                apiCallBack?.success()
                            }

                            override fun onError(t: Throwable) {
                                apiCallBack?.fail(t)
                            }
                        })
                }

                override fun dataIsNull(t: BaseBean<out ServerGoods>) {
                    super.dataIsNull(t)
                }

                override fun onError(t: Throwable) {
                    super.onError(t)
                }
            })

    }

    private fun d(msg: String? = "null") {
        CommUtils.println("CateProductApi->", msg!!);
    }


}